
<html>
<div id="loading">
<img src=images/loading.gif> <font color=#008080 size=3><b> Please wait a second ...</b></font>
</div>
<script>
function hideLoading()
{
  var disp = document.getElementById('loading');
  disp.innerHTML = '';
}

</script>

<body>

<?php require_once '../yubiphpbase/appinclude.php';
require_once '../yubiphpbase/yubi_lib.php';
include 'head.htm';

if (($usrid = getUsrIdFromSession()) <= 0) {
	echo TIMEDOUT;
	exit;
}

$_SESSION['tab'] = 0;
$act = getHttpVal('act', 'New');
$start = getHttpVal('start', 0);
$id=getHttpVal('id',-1);
//echo 'act='.$act.', id='.getHttpVal('id',-1).', counter='.getHttpVal('counter',-1);

if (strcmp($act,'Update')==0 && $id > 0) {
  // pName pHost pPort pProtocol pBaseDN pUserDN pPassword pSchedule pTimeout pFilter pNotes
  writeLog("ListUserToken::Main Update call", true);
  $pName = getHttpVal('pName', '');
  $pHost = getHttpVal('pHost', '');
  $pPort = getHttpVal('pPort', 389);
  $pProtocol = getHttpVal('pProtocol', 3);
  $pBaseDN = getHttpVal('pBaseDN', '');
  $pUserDN = getHttpVal('pUserDN', '');
  $pPassword = getHttpVal('pPassword', '');
  $pSchedule = getHttpVal('pSchedule', '');
  $pTimeout = getHttpVal('pTimeout', 1);
  $pFilter = getHttpVal('pFilter', '');
  $pNotes = getHttpVal('pNotes', ''); 
  
  $stmt = 'UPDATE userimportconf SET '.
	'host='.mysql_quote($pHost).
	', port='.$pPort.
	', protocol='.$pProtocol.
	', base_DN='.mysql_quote($pBaseDN).
	', user_DN='.mysql_quote($pUserDN).
	', password='.mysql_quote($pPassword).
	', schedule_type='.mysql_quote($pSchedule).
	', timeout='.$pTimeout.
	', filter='.mysql_quote($pFilter).
	', notes='.mysql_quote($pNotes);
  $stmt .= ' WHERE policy_id='.$id;
  
  if ($r = query($stmt)) {
    $_SESSION['alert'] = 'Configuration-'.$pName.' was updated successfully';
  } else {
    $_SESSION['alert'] = 'Configuration update failed! '.$contactAdm;
  }
  
  $act = 'findkey';
  $attrName=getHttpVal('attr_name', 'id');
  $attrVal=getHttpVal('attr_val', $_SESSION['client']);
  
} elseif (strcmp($act,'Delete')==0 && $id > 0) {

  writeLog("ListUserToken::Main Delete call", true);

  $user = getHttpVal('pName', '');
  
  if (delPolicy($id)) {
	$_SESSION['alert'] = 'Configuration-'.$user.' deleted successfully';
  } else {
	$_SESSION['alert'] = 'Failed to delete Configuration-'.$user.'! '.$contactAdm;
  } 
	
  $act = 'findkey';
  $attrName=getHttpVal('attr_name', 'id');
  $attrVal=getHttpVal('attr_val', $_SESSION['client']);
    
  showAlert(getAlert());

} elseif (strcmp($act,'Add')==0) {

  writeLog("ListUserToken::Main Add called", true);
  ///	pName pHost pPort pProtocol pBaseDN pUserDN pPassword pSchedule pTimeout pFilter pNotes
  $pName = getHttpVal('pName', '');
  $pHost = getHttpVal('pHost', '');
  $pPort = getHttpVal('pPort', 389);
  $pProtocol = getHttpVal('pProtocol', 3);
  $pBaseDN = getHttpVal('pBaseDN', '');
  $pUserDN = getHttpVal('pUserDN', '');
  $pPassword = getHttpVal('pPassword', '');
  $pSchedule = getHttpVal('pSchedule', '');
  $pTimeout = getHttpVal('pTimeout', 1);
  $pFilter = getHttpVal('pFilter', '');
  $pNotes = getHttpVal('pNotes', ''); 
  
  $stmt = 'INSERT INTO userimportconf (policy_name, host, port, protocol, base_DN, user_DN, password, schedule_type, timeout, filter, notes) '.
      'VALUES('.mysql_quote($pName).
      ', '.mysql_quote($pHost).
      ', '.$pPort.
      ', '.$pProtocol.
      ', '.mysql_quote($pBaseDN).
      ', '.mysql_quote($pUserDN).
      ', '.mysql_quote($pPassword).
      ', '.mysql_quote($pSchedule).
      ', '.$pTimeout.
      ', '.mysql_quote($pFilter).
      ', '.mysql_quote($pNotes).')';
  
  writeLog("ListUserToken::Main Add Qry :: ".$stmt, true);
  
  if ($r = query($stmt)) {
  	//mysql_free_result($r);
    $_SESSION['alert'] = 'Policy-'.$loginName.' with name-'.$pName.' is added successfully';
    
    $stmt = 'INSERT INTO clientpolicymap (policy_id, client_id) '.
      'VALUES('.mysql_insert_id().','.$_SESSION['client'].')';
      
    if ($r = query($stmt)) {
      writeLog("ListUserToken::Main Map Qry :: ".$stmt, true);	
    }
    
  } else {
    $_SESSION['alert'] = 'Configuration adding failed! '.$contactAdm;
  }
  
  writeLog("ListUserToken::Main Add Status :: ".$r, true);  
  $act = 'findkey';
  $attrName=getHttpVal('attr_name', 'id');
  $attrVal=getHttpVal('attr_val', $_SESSION['client']);
    
  showAlert(getAlert());

} else {
  writeLog("ListUserToken::Main selecting call call", true);  
  if (strcmp($act,'Retrieve')==0) {
  	
    writeLog("UserImportPolicy::Main Retrieve call", true);
    $id_type = getHttpVal('idtype', 'policyName');
    $searchtxt = getHttpVal('searchtxt', 1);
    
    $act = 'findkey';
    $attrName=getHttpVal('attr_name', $id_type);
    $attrVal=getHttpVal('attr_val', $searchtxt);    
    
    //idtype, searchtxt
  } else if (strcmp($act,'Import')==0) { /// Import setting 
    writeLog("UserImportPolicy::Main Retrieve call", true);
    $id_type = getHttpVal('idtype', 'policyName');
    $searchtxt = getHttpVal('searchtxt', 1);
    
    $act = 'import';
    $attrName=getHttpVal('attr_name', $id_type);
    $attrVal=getHttpVal('attr_val', $searchtxt);    
  }
}

if (showClientPolicy($act, $start, $attrName, $attrVal) == 0) {
    echo '<h4>No Configuration!</h4>';
}

// If client id = 0, meaning it's the root user, display all clients
function displayPolicy($row, $toggle, $mode) {
  //echo '<br> Mode'.$mode;
  $client = $_SESSION['client'];
  $pid = $row['policy_id'];
  if ((NULL != $row) || $mode) {
  	$readonly = 'readonly';
  }
  
  if ($mode) {
  	$edit_control = 'readonly';
  }
  
  
  echo '<tr'.($toggle ? ' bgcolor=#eeeeee>' : '> <td>');
  if(!$mode){
  	echo '<form method=POST action=user_import_policy.php>';
  } else {
  	echo '<form method=POST action=ldap_user_import.php>';
  }
  
  echo '<input name=act type=hidden value=upd_key>'.
    '<input name=clientId type=hidden value='.$client.'>'.
    '<input name=id type=hidden value='.$pid.'>'.
    '<input name=user type=hidden value='.$row['policy_name'].'>'.
    '<table border=0 width=100%><tr>'.
    '<td align=right valign=center><font size=2>';
  
  /*
  if ($keyId == $_SESSION['keyid']) {
  	echo '<img src=images/yubiright_16x16.gif title="This is the admin Yubikey you are using to log in!"><p>';
  } else if (isAdmKey($keyId)) {
  	echo '<img src=images/admkey.gif title="This is an admin Yubikey"><p>';
  }*/
  
  ///  <tag Policy Name>
  echo  'Configuration Name: </td>'; /// Policy Name ?readonly
  echo  '<td><input name=pName '.$readonly.' id=pName size=50 value='.$row['policy_name'].'></td> </tr>'; 
  /// </tag Policy Name>
  
  writeLog("UserImportPolicy::displayPolicy Policy Name = ".$row['policy_name'] , true);

  ///  <tag Host>
  echo  '<tr><td align=right valign=center><font size=2>Host: </td>';
  echo  '<td><input name=pHost '.$edit_control.' id=pHost size=50 value='.$row['host'].' ></td> </tr>'; 
  /// </tag Host>

  ///  <tag Port>
  echo  '<tr><td align=right valign=center><font size=2>Port: </td>';
  echo  '<td><input name=pPort '.$edit_control.' id=pPort size=10 value='.$row['port'].' ></td> </tr>'; 
  /// </tag Port>

  if (!$mode) {

    ///  <tag Protocol>
    echo  '<tr><td align=right valign=center><font size=2>Protocol: </td>';
    echo '<td><select name=pProtocol>';
    echo '<option value="2" '.($row['protocol']==2 ? 'selected' : '').'>2'.
       '<option value="3" '.($row['protocol']==3 ? 'selected' : '').'>3';
    echo '</select></td> </tr>'; 
    /// </tag Protocol>
  }

  ///  <tag Base DN>
  echo  '<tr><td align=right valign=center><font size=2>Base DN: </td>';
  echo  '<td><input name=pBaseDN id=pBaseDN size=50 value='.$row['base_DN'].' ></td> </tr>'; 
  /// </tag Base DN>

  ///  <tag User DN>
  echo  '<tr><td align=right valign=center><font size=2>User DN: </td>';
  echo  '<td><input name=pUserDN id=pUserDN size=50 value='.$row['user_DN'].' ></td> </tr>'; 
  /// </tag User DN>

  ///  <tag Password>
  echo  '<tr><td align=right valign=center><font size=2>Password: </td>';
  if (!$mode) {
  	echo  '<td><input type=password name=pPassword id=pPassword size=25 value='.$row['password'].' ></td> </tr>';
  } else {
  	echo  '<td><input type=password name=pPassword id=pPassword size=25></td> </tr>';
  }
   
  /// </tag Password>

  if (!$mode) {
    ///  <tag Schedule>
    echo  '<tr><td align=right valign=center><font size=2>Schedule: </td>';
    echo '<td><select name=pSchedule>';
    echo '<option value="none" '.($row['schedule_type']==demo ? 'selected' : '').'>None'.
       '<option value="weekly" '.($row['schedule_type']==weekly ? 'selected' : '').'>Weekly'.
       '<option value="daily" '.($row['schedule_type']==daily ? 'selected' : '').'>Daily'.
       '<option value="hourly" '.($row['schedule_type']==hourly ? 'selected' : '').'>Hourly';
    echo '</select></td> </tr>'; 
    /// </tag Schedule>

    ///  <tag Timeout>
    echo  '<tr><td align=right valign=center><font size=2>Timeout: </td>';
    echo  '<td><input name=pTimeout id=pTimeout size=10 value='.$row['timeout'].' ></td> </tr>'; 
    /// </tag Timeout>
  	
  }
  
  ///  <tag Filter>
  echo  '<tr><td align=right valign=center><font size=2>Filter: </td>';
  echo  '<td><input name=pFilter id=pFilter size=50 value='.$row['filter'].' ></td> </tr>'; 
  /// </tag Filter>
  
  if (!$mode) {
    ///  <tag Notes>
    echo  '<tr><td align=right valign=center><font size=2>Notes: </td>';
    echo  '<td><input name=pNotes id=pNotes size=50 value="'.$row['notes'].'" ></td> </tr>'; 
    /// </tag Notes>
  }
  
  if (NULL != $row) {
  	if (!$mode) {
      echo '<tr><td align=left/><td align=left valign=center><input name=act type=submit value=Update class=buttonLinkSmall>&nbsp;'.
    	 '<input name=act type=submit value=Delete class=buttonLinkSmall></td></tr></table></form></td></tr>';
  	} else {
  	   ///  <tag LogingIdentifier>
      echo  '<tr><td align=right valign=center><font size=2>Loging Name Identifier: </td>';
      echo  '<td><input name=pLoginNameID id=pLoginNameID size=50 value="sAMAccountName" ></td> </tr>'; 
      /// </tag LogingIdentifier>
  		
      echo '<tr><td align=left/><td align=left valign=center><input name=act type=submit value=GetUsers class=buttonLinkSmall>&nbsp;'.
    	 '</td></tr></table></form></td></tr>';
  	}
  	
  } else {
  	echo '<tr><td align=left/><td align=left valign=center><input name=act type=submit value=Add class=buttonLinkSmall>&nbsp;'.
    	 '</td></tr></table></form></td></tr>';
  } 
  	
} // End displayPolicy

// $act: operation code = findkey | list_keys
// $otp: modhex OTP from a Yubikey
function showClientPolicy($act, $start, $attrName, $attrVal) {
  $client = $_SESSION['client'];
  //echo ' <br> act='.$act.', attrName='.$attrName.', val='.$attrVal;
  
  if ($act != 'New') {
    $stmt = 'SELECT policy_id, policy_name, host, port, protocol, base_DN, user_DN, password, schedule_type, timeout, filter, notes FROM userimportconf uconf';
    $stmt .= ' WHERE (uconf.policy_id in (select policy_id from clientpolicymap c WHERE c.client_id='.$client.')) ';
  
    if (($act == 'findkey') || ($act == 'import')) {
	  if (isRootAdm() && $attrName=='client_id' && is_numeric($attrVal)) { // adm can see keys of any client
  		  //$stmt .= 'AND client_id='.$attrVal; /// need to think about it
  	  } else if ($attrName=='policyName') {
  		  $stmt .= 'AND uconf.policy_name='.mysql_quote($attrVal);
  	  } 
    } else {
  	  $act = 'list_keys';
    }
  
    $stmt .= ' LIMIT '.$start.', 1';
  
    writeLog($stmt, true);
  }
  
  echo '<table border=0 width=100%><tr><td valign=top colspan=9 align=left><font size=2>';
  funcBar($act, $attrName, $attrVal);
  echo '</td></tr>';
   
  ////// Find matching yubikeys
  //   
  //if (strlen($attrVal) < 1) { return 1; }
  if ($act == 'New')
  {
  	// Display blank record
  	displayPolicy(NULL, 0, 0); 
  } else {
    $r = query($stmt);
    $n=mysql_num_rows($r);
    writeLog("UserImportPolicy::showClientPolicy Row Count = ".$n , true);  	
  
    $i=0;
    while ($row=mysql_fetch_assoc($r)) { 
      if ($act == 'import') {
      	displayPolicy($row, 0, 1);
      } else {
      	displayPolicy($row, 0, 0);
      }
	  $i += 1;
    }
  
    mysql_free_result($r);
  }
  
  echo '</table>';
  
  if ($act != 'New')
  {
  	if ($i == 0) {
  		echo '<font color=#008080 size=2><b>Showing ' . $i . ' record(s)</b></font><br><br>';
  		echo '<font color=#008080 size=2><b><a href=user_import_policy.php>&gt;&gt; Add new policy</a></b></font><br><br>';
  	} else{
  		echo '<font color=#008080 size=2><b>Showing ' . $i . ' record(s)</b></font><br><br>';
  	}
  }
    
  if ($i < MAX_PER_PAGE) {
  	return ($i > 0 ? $i : -1);
  }
  
  echo '<h3><a href=#top>^ TOP</a><center><a name=BOT></a>';
  
  if ($attrName =='client_id') {
  	$filter = '&act=findkey&attr_name=client_id&attr_val='.$attrVal;
  } else {
  	$filter ='';
  }
  
  if ($start > 0) {
  	if (($s = $start - MAX_PER_PAGE) < 0) { $s = 0; }  	
  	echo '<a href=user_import_policy.php?act=list_keys&start='.$s.$filter.'>PREV</a> | ';
  }

  if ($i >= MAX_PER_PAGE-1) {  	
  	echo '<a href=user_import_policy.php?act=list_keys&start='.($start+MAX_PER_PAGE).$filter.'>NEXT</a>';
  }
  
  echo '</h3></center>';
    
  return $n;

} // End showMyAccts

// op = list_keys, findkey
function funcBar($act, $attrName, $attrVal) {
	global $page;
	$confName = '';
	
	if($attrName=='policyName') {
  		$confName = $attrVal;
  	} 
//    echo '<hr size=1><table><tr><td valign=top><img src=images/arrow.jpg></td>'.
//      '<td nowrap valign=bottom><a href=#DOWN onclick="javascript:showAddUserToken(0,'.$_SESSION['client'].');">'.
//      '<b><font color=#008080 size=2><b> Add a yubikey mapped >></b></font></a>'.
//      '<p><div id=mapkey></div></td></tr></table>';
      	
	echo '<table border=0 width=80%>';
//	  '<tr><td colspan=9 height=10></td></tr>';

    echo '<tr>';

//	if ('list_keys' != $act) {
//    	echo '<tr><td valign=top> ';
//    	divBut(150, $page.'?act=list_keys','<font size=2>>> List of Mapped Users</font>');
//    	echo '</td><td width=10></td><td width=30 nowrap valign=top>&nbsp;or&nbsp;</td>';
//	} Client has <No> import configurations.

	$policyList = getPolicyNames($_SESSION['client']);
	writeLog("UserImportPolicy::Policy Names = ".count($policyList) , true);

    echo '<tr><td colspan=9 align=left>'.     
      '<form autocomplete=off method=POST action=user_import_policy.php>'.
	  '<table border=0 width=90%>'.
	  '<tr><td colspan=9 align=center><font color=#008080 size=2><b>'.
	   'Import configuration management for the Client:</font></b> <br>'.
	  '</td></tr>'.
	  '<tr><td align=right>' .
	  '<font size=2 color=#AA0000>'.
	  	'» Configuration Name : </font><br>'.
		'</td><td align=center>';
	
	if (count($policyList) == 0) {
		echo '<input name=searchtxt id=searchtxt size=50>';
	} else {
		echo '<select name=searchtxt>';
		foreach ($policyList as &$value) {
			echo '<option value="'.$value.'" '.($confName==$value ? 'selected' : '').'> '.$value;
		}
		unset($value); 
    	echo '</select>';
	}

	echo '</td><td align=left>' .
	  '<input name=act type=submit value=Retrieve class=buttonLinkSmall><br><br>'.
	  '<input name=act type=submit value=Import class=buttonLinkSmall>'.
	  '<tr><td align=center><font color=#008080 size=2> This client has '.count($policyList).' import configuration(s).</font>'.	  
	  '</td></tr></table>'.
	  '</form>'.
	  
      '</td></tr>';  	
  	
	echo '</table><hr size=1>';
}

?>

<script>
hideLoading();
</script>
</body>
</html>
